﻿<template>
    <div class="grWorkCard">
        <vxe-grid id="xGrid"
                  class="xGrid"
                  ref="xGrid"
                  :loading="loading"
                  border
                  resizable
                  show-overflow
                  keep-source
                  highlight-hover-row
                  :row-class-name="rowClassName"
                  :height="tableH"
                  align="center"
                  :print-config="{}"
                  :import-config="{}"
                  :export-config="{}"
                  :custom-config="{storage: true}"
                  :toolbar-config="tableToolbar"
                  :scroll-y="{ enabled: false }"
                  :columns="tableColumn"
                  :checkbox-config="{labelField: '', highlight: true, range: true}"
                  :seq-config="seqConfig"
                  :menu-config="menuConfig"
                  :data="tableData"
                  @page-change="handlePageChange"
                  @edit-actived="editActived"
                  @edit-closed="editClosed"
                  :row-config="{isCurrent: true, isHover: false}"
                  @checkbox-range-change="checkboxChange"
                  @checkbox-change="checkboxChange"
                  @checkbox-all="checkboxAll"
                  @cell-click="handleCellClick"
                  @cell-dblclick="handleCellDbClick">
            <template v-slot:toolbar_buttons>
                <div class="tableToolbar">
                    <div style="min-width: 55px; font-weight: 700; font-size: 16px; font-family: 'Noto Sans SC'; color: #303133;">子任务</div>
                    <el-button style="margin-left:10px" type="primary" size="mini" @click="createAdd()">新增</el-button>
                    <el-button type="primary" size="mini" class="tableToolbarTextL" :disabled="selectedItems.length != 1" @click="openShowCount()">复制</el-button>
                    <el-button type="danger" size="mini" class="tableToolbarTextL" :disabled="selectedItems.length === 0" @click="deleteDeList()">批量删除</el-button>
                </div>
            </template>

            <template #operate="{ row }">
                <!--<el-link type="primary" class="elLinkBTN" @click="edit(row)">编辑</el-link>
            <el-link type="danger" class="elLinkBTN" @click="deleteDeJob(row)">删除</el-link>-->
            </template>


        </vxe-grid>
        <vxe-modal v-model="tableShow" :loading="formLoading" :title="formTitle" width="900" :show-close="false" resize destroy-on-close>
            <template #default>
                <vxe-form ref="myform" :data="formInfo" :items="formItems" title-width="140" title-align="center" :rules="formRules">

                </vxe-form>
                <div style="text-align:right">
                    <el-button size="mini" @click="dialogFormClose">取 消</el-button>
                    <el-button size="mini" type="primary" @click="dialogFormSave">确 定</el-button>
                </div>
            </template>
        </vxe-modal>

        <vxe-modal v-model="showCount"  title="复制子任务数量" width="300" :show-close="false" resize destroy-on-close>
            <template #default>
                <el-input placeholder="请输入"
                          style="margin:10px;width:95%"
                          v-model="count">
                </el-input>
                <div style="text-align:right">
                    <el-button size="mini" @click="count = null,showCount = false">取 消</el-button>
                    <el-button size="mini" type="primary" @click="copySubTask">确 定</el-button>
                </div>
            </template>
        </vxe-modal>
    </div>
</template>
<script>
    import prjAPI from '../../../request/Project/PrjAPI.js';
    export default {
        props: {
            canEdit: { type: String, default: true },
            taskInfo: { type: Object, default: null },
            tableH: { type: Number, default: 0 },
        },
        data() {
            return {
                count: null,
                showCount:false,
                nowSelectTaskID: null,
                loading: false,
                formLoading: false,
                formTitle: '新增',
                searchName: '',
                formInfo: {},
                tableShow: false,
                tableColumn: [
                    { field: 'checkbox', type: 'checkbox', title: '', fixed: 'left', width: 40 },
                    //{ field: 'drag', title: '排序', width: 100, fixed: 'left', visible: false, titlePrefix: { content: '拖动排序' }, slots: { default: 'dragBtn' } },
                    { type: 'seq', title: '序号', width: 60, fixed: 'left' },
                    { field: 'sTaskEquip', title: '设备', minWidth: 120, editRender: {}, },
                    { field: 'surfaceStatus', title: '表面状态', minWidth: 120, editRender: {}, },
                    { field: 'sTaskTime', title: '创建时间', width: 120, formatter: ({ row }) => { return this.toDate(row.sTaskTime) } },
                    { field: 'createUID', title: '创建人', width: 130, formatter: ({ row }) => { return this.getUser(row.createUID) } },
                    { field: 'remark', title: '备注', minWidth: 160, editRender: {}, },
                    //{ title: "操作", fixed: "right", width: 120, slots: { default: "operate" } },
                ],
                editConfig: {
                    enabled: false,
                    trigger: 'click',
                    mode: 'row',
                    showStatus: true
                },
                tableToolbar: {
                    refresh: {
                        query: () => this.getData()
                    },
                    import: false,
                    export: false,
                    print: false,
                    custom: false,
                    slots: {
                        buttons: 'toolbar_buttons'
                    }
                },
                tablePage: {
                    enabled: true,
                    total: 0,
                    currentPage: 1,
                    pageSize: 50,
                    align: 'right',
                    pageSizes: [50, 80],
                    layouts: [],
                    perfect: true,
                    slots: {
                       
                    }
                },
                menuConfig: {
                    enabled: false,
                    body: {
                        disabled: false,
                        trigger: 'default',
                        options: [
                            [
                                { name: '在上方插入行', code: 'above', prefixIcon: 'el-icon-arrow-up' },
                                { name: '在下方插入行', code: 'below', prefixIcon: 'el-icon-arrow-down' },
                            ],
                            [
                                { name: '应用于其他', code: 'use', prefixIcon: 'iconfont icon-fuzhi' },
                                { name: '应用于本页全部', code: 'useAll', prefixIcon: 'iconfont icon-niantie-1' },
                            ],
                            [
                                { name: '置顶', code: 'setTop', prefixIcon: 'iconfont icon-zhiding' },
                                { name: '移动', code: 'move', prefixIcon: 'el-icon-rank' },
                                { name: '删除', code: 'delete', prefixIcon: 'el-icon-delete' },
                            ]
                        ]
                    }
                },
                tableData: [],
                editActive: {
                    PGCS: false,
                    KYYJ: false
                },
                seqConfig: {
                    seqMethod({ rowIndex }) {
                        return (rowIndex + 1).toString().padStart(3, '0')
                    }
                },
                repairMeasure: [],
                formItems: [
                    { field: 'sTaskEquip', title: '设备', span: 12, itemRender: { name: '$input', props: { placeholder: '请输入' } } },
                    { field: 'surfaceStatus', title: '表面状态', span: 12, itemRender: { name: '$input', props: { placeholder: '请输入' } } },
                    { field: 'sTaskTime', title: '创建时间', span: 12, itemRender: { name: '$input', props: { type: 'date', labelFormat: 'yyyy-MM-dd', placeholder: '请选择日期' } } },
                    { field: 'remark', title: '备注', span: 12, itemRender: { name: '$input', props: { placeholder: '请输入' } } },
                ],
                formRules: {
                    sTaskEquip: [{ required: true, message: '请填写设备' }],
                    surfaceStatus: [{ required: true, message: '请填写表面状态' }],
                },

                showRelay: false,
                loadingRelay: false,
                nowSelectItem: null,
                loadingProf: true,
                prof: [],

                loadingWC: true,
                workCards: [],

                selectedItems: [],
                editItemNum: 0,

                tableModeMessage: null,
                nowSelectedRow: null,
                nowSelectedField: '',
                mode: '',
                modeOps: {
                    move: '移动',
                    use: '应用'
                },
                canUseField: {
                    isImportant: true,
                    itemName: true,
                    measure: true,
                    investigaion: true,
                    isInvestigate: true
                },
                userList:[],
                showDragBtn: false,
                dragDataForm: null,

                otherFaultShow: false,
                faultFilter: null,
                placeholder2: '请输入故障项目名称查询',
                faultLoading: false,
                faultTable: [
                    { field: 'checkbox', type: 'checkbox', title: '', width: 40, fixed: 'left' },
                    { type: 'seq', title: '序号', width: 60, fixed: 'left' },
                    { field: 'itemName', minWidth: 360, title: '故障项目' },
                    { field: 'wcid', minWidth: 180, title: '所在工卡', formatter: ({ row }) => { return this.wcidArr[row.wcid] } },
                    { field: "profID", width: 200, title: "专业", formatter: ({ row }) => { return this.format(this.prof, row.profID) } },
                ],
                tableToolbar2: {
                    refresh: {
                        query: () => this.getOtherFault()
                    },
                    import: false,
                    export: false,
                    print: false,
                    custom: true,
                    slots: {
                        buttons: 'toolbar_buttons'
                    }
                },
                faultTablePage: {
                    total: 0,
                    currentPage: 1,
                    pageSize: 50,
                    align: 'right',
                    pageSizes: [50, 80],
                    layouts: ['Sizes', 'PrevJump', 'PrevPage', 'JumpNumber', 'NextPage', 'NextJump', 'FullJump', 'Total'],
                    perfect: true
                },
              
                faultList: [],
                wcidArr: [],
                profType: '',
                selectedProjs: [],
                isFaultImportant: null,
                toolTipClose: '可点击[esc]按钮快速关闭当前弹窗',
            };
        },
        watch: {
            taskInfo(data) {
                if (data) {
                    this.getData();
                }
            },
            canEdit(data) {
            }
        },
        created() {
            this.watchKeyDown();
        },
        mounted() {
            //this.setTableColumn();
            //this.initRowDrop();
            this.getData();
            if (this.workCardInfo) {
                //this.getData(0);
                //this.getAllRepairMeasure();
            }
        },
        beforeDestroy() {
        },
        methods: {
            visibilityChange() {

            },
            selectstartFunc() {
                var e = e || window.event;
                e.preventDefault();
            },
            getData(type) {
                if (!this.taskInfo.taskID) {
                    return false
                };
                this.tableData = [];
                this.loading = true;
                var whereStr = "isDelete = 0 ";

                var params = {
                    taskid: this.taskInfo.taskID
                };
                prjAPI.getTestSubTaskList(params).then(res => {
                    this.tableData = res;
                    if (res) {
                        this.$refs.xGrid.setCurrentRow(res[0]);
                        this.$emit('selectSubTask', res[0]);
                    } else {
                        this.$emit('selectSubTask', {});
                    };
                    this.loading = false;
                }).catch(err => {
                    this.loading = false;
                });
            },
            createAdd() {
                this.formInfo = {
                    prjID: this.taskInfo.prjID,
                    taskID: this.taskInfo.taskID,
                    sTaskEquip: '',
                    surfaceStatus: '',
                    remark: '',
                    isDelete: false,
                    sTaskTime: new Date(), 
                };
                this.tableShow = true;
                this.formTitle = '新增子任务';

            },
            handleCellDbClick({ row }) {
                this.edit(row);
            },

            edit(row) {
                this.tableShow = true;
                this.formTitle = '编辑子任务';
                this.formInfo = row;
            },
            deleteDeJob(row) {
                this.$confirm(`是否删除该条数据?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.loading = true;
                    prjAPI.deleteTestSubTask(row.sTaskID).then(res => {
                        if (!res) {
                            this.$message({ type: 'warning', message: '删除失败!' });
                        }
                        this.$message({ type: 'success', message: '删除成功!' });
                        this.getData(0);
                    });
                }).catch(() => {
                    this.loading = false;
                });
            },
            deleteDeList() {
                var title = `是否删除已选中的 ${this.selectedItems.length} 条数据`;
                this.$confirm(title, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    var data = this.selectedItems.map(e => e.sTaskID);
                    this.loading = true;
                    prjAPI.deleteTestSubTaskList(data).then(res => {
                        if (!res) {
                            this.$message({ type: 'warning', message: '删除失败!' });
                        }
                        this.$message({ type: 'success', message: '删除成功!' });
                        this.loading = false;
                        this.getData(0);
                    }).catch(err => {

                    });
                }).catch(() => { });
            },
            handleCellClick({ row, column }) {
                if (column.field === "checkbox") return;
                this.$refs.xGrid.setCurrentRow(row);
                this.$emit('selectSubTask', row);
            },
            openShowCount() {
                this.showCount = true;
                this.count = null;

            },
            copySubTask() {
                var loadingFullScreen = this.$loading({
                    lock: true,
                    text: '正在复制子任务',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.3)'
                });
                var params = {
                    STaskID: this.selectedItems[0].sTaskID,
                    Count: this.count
                };
                prjAPI.exeCopySubTask(params).then(res => {
                    loadingFullScreen.close();
                    this.$message({ type: 'success', message: '复制完成!' });
                    this.showCount = false;
                    this.getData(0);
                }).catch(err => {

                });
            },
            dialogFormClose() {
                this.tableShow = false;
                this.formInfo = {};
            },

            dialogFormSave() {
                this.$refs.myform.validate().then(suc => {
                    if (!suc) {
                        this.formInfo.sTaskID ? this.isAdd = true : this.isAdd = false;
                        this.formLoading = true;
                        prjAPI[this.formInfo.sTaskID ? 'updateTestSubTask' : 'createTestSubTask'](this.formInfo).then(res => {
                            if (res) {
                                this.$message({ type: 'success', message: this.isAdd ? '修改成功' : '创建成功' });
                                this.formLoading = false;
                                this.tableShow = false;
                                this.getData(0);
                            } else {
                                this.$message({ type: 'warning', message: this.isAdd ? '修改失败' : '创建失败' });
                                this.formLoading = false;
                                this.tableShow = false;
                                this.getData(0);
                            }

                        }).catch(err => {
                            this.formLoading = false;
                        });
                    }
                }).catch(() => { });
            },

            rowClassName({ row }) {
                if (row === this.nowSelectedRow) {
                    return 'colMoveMode';
                }
            },
            handlePageChange({ currentPage, pageSize }) {
                this.tablePage.currentPage = currentPage;
                this.tablePage.pageSize = pageSize;
                this.getData();
            },
           
            editActived({ row, column, rowIndex }) {
                //this.editActive = {
                //    PGCS: column.field === 'measure',
                //    KYYJ: column.field === 'investigaion'
                //};
            },
            editClosed({ row, rowIndex }) {
                this.editActive = {
                    PGCS: false,
                    KYYJ: false
                };
                this.getEditNum();
            },
            getEditNum() {
                if (this.$refs.xGrid) {
                    var { insertRecords, updateRecords } = this.$refs.xGrid.getRecordset();
                    this.editItemNum = insertRecords.length + updateRecords.length;
                }
            },
            getAddEditNum() {
                this.getEditNum();
                this.$emit('getEditNum', this.editItemNum)
            },

            getAllRepairMeasure() {
                repMeasureAPI.getAllByProf({
                    profID: this.workCardInfo.profID
                }).then(res => {
                    this.repairMeasure = res.map(item => {
                        return {
                            value: item.measure
                        };
                    });
                }).catch(err => { });
            },
            querySearch(queryString, cb) {
                cb(this.repairMeasure);
            },
            focusEvent(type) {
                this.editActive[type] = true;
                if (type === 'PGCS') {
                    this.$refs.vxepulldown.showPanel();
                }
            },
            focusEvent2(type) {
                this.editActive[type] = false;
                if (type === 'PGCS') {
                    this.$refs.vxepulldown.hidePanel();
                }
            },
            selectMeasure(row, item) {
                var txt = document.getElementsByName('textareaG')[0];
                if (txt.selectionStart || txt.selectionStart === 0) {
                    var startPos = txt.selectionStart;
                    var endPos = txt.selectionEnd;
                    row.measure = txt.value.substring(0, startPos) + item.value + txt.value.substring(endPos, txt.value.length);
                    this.$nextTick();
                    txt.focus()
                    txt.setSelectionRange(endPos + item.value.length, endPos + item.value.length);
                } else {
                    row.measure += item.value;
                }
                this.$refs.vxepulldown.hidePanel();
            },
            closeEdit(type) {
                //遮罩层
                //this.editActive[type] = false;
                //this.$refs.xGrid.clearEdit();
            },

            goBack() {
                this.loading = false;
                this.selectedItems = [];
                this.getData();
            },

            checkboxChange({ checked, row }) {
                this.selectedItems = this.$refs.xGrid.getCheckboxRecords();
               
            },
            checkboxAll({ checked }) {
                this.selectedItems = this.$refs.xGrid.getCheckboxRecords(true);
               
            },
            clearContext(row) {
                row.measure = '';
            },
            closeContext() {
                this.editActive.PGCS = false;
            },
            clearContext2(row) {
                row.investigaion = '';
            },
            closeContext2() {
                this.editActive.KYYJ = false;
            },
            fx() {
                var tableData = this.$refs.xGrid.getTableData().tableData;
                this.selectedItems = [];
                for (var i = 0; i < tableData.length; i++) {
                    if (this.$refs.xGrid.isCheckedByCheckboxRow(tableData[i])) {
                        this.$refs.xGrid.setCheckboxRow(tableData[i], false);
                    } else {
                        this.$refs.xGrid.setCheckboxRow(tableData[i], true);
                        this.selectedItems.push(tableData[i]);
                    }
                };
                
            },
            checkboxChange2({ checked, row }) {
                this.selectedProjs = this.$refs.xGrid2.getCheckboxRecords();
            },
            checkboxAll2({ checked }) {
                this.selectedProjs = this.$refs.xGrid2.getCheckboxRecords(true);
            },
            
            
            
            

            disabledZFGK(row) {
                var obj = this.projectGRJSON.workCardStatus.find(e => e.value === row.status);
                return obj.canEdit;
            },
            tooltipZFGK(row) {
                var obj = this.projectGRJSON.workCardStatus.find(e => e.value === row.status);
                var tooltip = obj.canEdit === false ? `该工卡状态为“${obj.label}”,故无法转发` : '';
                return tooltip;
            },
            classZFGK(row) {
                return {
                    profRelay: true,
                    profRelayDisabled: row.status === 3 || row.status === 4 || row.wcid === this.workCardInfo.wcid
                };
            },
            showOtherFaultModal() {
                this.otherFaultShow = true;
                this.faultFilter = null;
                this.getOtherFault(0);
            },
            getOtherFault(type) {
                this.faultList = [];
                this.wcidArr = [];
                this.faultLoading = true;
                if (type === 0) {
                    this.faultTablePage.currentPage = 1;
                };
                var parmas = {
                    pageIndex: this.faultTablePage.currentPage - 1,
                    pageSize: this.faultTablePage.pageSize,
                    itemName: this.faultFilter,
                    wcid: this.workCardInfo.wcid,
                    prjID: this.workCardInfo.projectID,
                    profID: this.profType ? this.profType : 0,
                    isImportant: this.isFaultImportant,
                };
                workCardAPI.getRepairItemPager(parmas).then(res => {
                    //var data;
                    //if (this.isFaultImportant === null) {
                    //    data = res;
                    //} else if (this.isFaultImportant === null) {
                    //    data = res.result.
                    //}
                    this.faultList = res.result.result;
                    this.wcidArr = res.wordCardNameDic;
                    this.faultTablePage.total = res.result.recordCount;
                    this.faultLoading = false
                }).catch(() => {
                    this.faultLoading = false;
                });
            },
            
            exportMethod() {
                var body = {
                    queryPara: this.faultFilter,
                    prjid: this.workCardInfo.projectID
                };
                var loadingFullScreen = this.$loading({
                    lock: true,
                    text: '正在导出',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.3)'
                });
                workCardAPI.getExportRepairItem(body).then(res => {
                    const blob = new Blob([res], { type: 'text/plain;charset=utf-8' });
                    if ('download' in document.createElement('a')) {
                        // 非IE下载
                        const elink = document.createElement('a');
                        elink.download = this.projectInfo.projectName + '故障项清单.xlsx';
                        elink.style.display = 'none';
                        elink.href = URL.createObjectURL(blob);
                        document.body.appendChild(elink);
                        elink.click();
                        URL.revokeObjectURL(elink.href);
                        document.body.removeChild(elink);
                    } else {
                        // IE10+下载
                        navigator.msSaveBlob(blob, this.projectInfo.projectName + '故障项清单.xlsx');
                    }
                    loadingFullScreen.close();
                }).catch(() => {
                    loadingFullScreen.close();
                    this.$message({ type: 'error', message: '导出失败' });
                });
            },
            format(ops, op, hasops) {
                var val = null;
                if (hasops) {
                    var options = ops.map((e) => {
                        return e.options;
                    }).flat().valueOf();
                    val = options.find((e) => e.profID === op);
                } else {
                    val = ops.find((e) => e.profID === op);
                }
                console.log(val);
                return val ? val.profName : "";
            },
            toDate(date) {
                return date ? moment(date).format("YYYY-MM-DD") : "";
            },
            getUser(date) {
                return date ? JSON.parse(sessionStorage.getItem('userList')).find(x => x.userid === date).realname : '';
            },
            watchKeyDown() {
                var _this = this;
                window.onkeyup = (e) => {
                    e.preventDefault(); // 阻止原有按键功能事件
                    var el = e || window.event || arguments.callee.caller.arguments[0];
                    if (el.keyCode === 27) {
                        _this.editActive.PGCS = false;
                        _this.editActive.KYYJ = false;
                    }
                };
            }
        },
        template: `#template`
    };
</script>
